package com.fau.om.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.fau.om.entity.MedicalAdmin;
import com.fau.om.entity.MedicalEnterpriseExtension;
import com.fau.om.entity.MedicalEnterpriseQueue;
import com.fau.om.service.IAlternatelyManagerService;

@Service
@Transactional(readOnly = true)
public class AlternatelyManagerService extends BaseService implements
		IAlternatelyManagerService {

	@SuppressWarnings("unchecked")
	@Override
	public List<MedicalEnterpriseQueue> findAllQueue(MedicalAdmin admin) {
		return this.iBaseDao.getBySql("from MedicalEnterpriseQueue a where a.eid=? ", null, admin.getEnterpriseId());
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void loginExt(String username, String extenNumId, String queue) {
		this.iBaseDao.updateHql("update MedicalAdmin a set a.phoneNumber=? where a.phoneNumber=? ", "0", extenNumId);
		this.iBaseDao.updateHql("update MedicalAdmin a set a.phoneNumber=? where a.username=? ", extenNumId, username);
		this.iBaseDao.updateHql("update MedicalEnterpriseExtension a set a.jobNum=?, a.queue=? where a.extension=? ", username, queue, extenNumId);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void loginOutExt(String username, String extenNumId, String queue) {
		this.iBaseDao.updateHql("update MedicalAdmin a set a.phoneNumber=? where a.username=? ", "0", username);
		this.iBaseDao.updateHql("update MedicalEnterpriseExtension a set a.jobNum=?, a.queue=? where a.extension=? ", "0", "0", extenNumId);
	}

	@Override
	public String findExtQueue(MedicalAdmin admin) {
		MedicalEnterpriseExtension bean = (MedicalEnterpriseExtension) this.iBaseDao.getObjectByHql("from MedicalEnterpriseExtension a where a.jobNum=? ", admin.getUsername());
		StringBuilder extQueue = new StringBuilder();
		if(null != bean) {
			extQueue.append(bean.getExtension());
			extQueue.append("|");
			extQueue.append(bean.getQueue());
		}
		return extQueue.toString();
	}

	@Override
	public String findCurExtension(String userId) {
		MedicalAdmin admin = (MedicalAdmin) this.iBaseDao.getObject(MedicalAdmin.class, userId);
		return admin.getPhoneNumber();
	}
	
}
